import json
import re

from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.cache import cache
from django.shortcuts import render
from django.views import View

from apps.areas.models import Area, Address
from utils import constants
from utils.response_code import RETCODE


class AreasView(View):
    """提供省市区数据"""

    def get(self, request):
        """提供省市区数据"""
        # 获取查询字符串area_id的值
        area_id = request.GET.get('prov_id')
        # print('>>>呵呵>>>', area_id)
        # 判断area_id是否存在 如果不存在就查询省级数据
        if not area_id:
            # 从redis取出缓存
            province_list = cache.get('province_list')
            # 如果没有缓存 就从数据库查询
            if not province_list:
                try:
                    province_model_list = Area.objects.filter(parent__isnull=True)  # 查询外键为空的  是省级数据
                    # 定义一个列表 存放数据
                    province_list = []
                    # 序列化省级数据
                    for province_model in province_model_list:
                        province_list.append({'id': province_model.id, 'name': province_model.name})
                    # 缓存数据进redis
                    cache.set('province_list', province_list, 3600)
                except Exception as e:
                    return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '省级数据读取错误'})
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '读取省级数据成功', 'province_list': province_list})
        else:
            # 提供市或者区的数据
            # 获取redis缓存数据
            sub_data = cache.get('sub_data_' + area_id)
            if not sub_data:
                try:
                    # 数据库查询
                    parent_model = Area.objects.get(id=area_id)  # 获取父级
                    sub_model_list = parent_model.subs.all()  # 获取所有子级的

                    #  序列化市或区数据
                    sub_list = []
                    for sub_model in sub_model_list:
                        sub_list.append({'id': sub_model.id, 'name': sub_model.name})
                    sub_data = {
                        'id': parent_model.id,
                        'name': parent_model.name,
                        'subs': sub_list
                    }
                    # 把数据缓存进redis
                    cache.set('sub_data_' + area_id, sub_list, 3600)
                except Exception as e:
                    return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '城市或区数据错误'})
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'sub_data': sub_data})


class CreateAddressView(View):
    """实现新增地址的后端逻辑"""

    def post(self, request):

        # 获取收货人名字
        receiver = request.POST.get('receiver')
        # 获取手机号
        mobile = request.POST.get('mobile')
        # 获取固定号码
        tel = request.POST.get('tel')
        # 获取邮箱
        email = request.POST.get('email')
        # 获取收货地址
        place = request.POST.get('place')
        # 获取省级，市级，县级
        province_id = request.POST.get('province_id')
        city_id = request.POST.get('city_id')
        district_id = request.POST.get('district_id')

        # print(444)

        # 保存地址信息
        try:
            address = Address.objects.create(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email

            )
            # print('aaa')
            # 判断用户是否有默认收货地址
            if not request.user.default_address:
                # print('bbb')
                request.user.default_address = address
                request.user.save()
                # print('ccc')
        except Exception as e:
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '新增地址失败'})

        # 把收货地址的响应传给前段，实现局部刷新
        address_dict = {
            'id': address.id,
            'title': address.title,
            'receiver': address.receiver,
            'province': address.province.name,
            'city': address.city.name,
            'district': address.district.name,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email
        }
        # print(555)
        # 返回响应结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'address': address_dict})


class UserAddress(LoginRequiredMixin, View):
    """用户收获地址"""

def post(self, request):
        # 获取参数
        print('进入了post方法')
        receiver = request.POST.get('name')
        province_id = request.POST.get('s_province')
        city_id = request.POST.get('s_city')
        district_id = request.POST.get('s_county')
        place = request.POST.get('address')
        mobile = request.POST.get('phone')
        email = request.POST.get('email_number')
        default = request.POST.get('default')
        print(receiver, 'name')
        print(province_id, 's_province')
        print(city_id, 's_city')
        print(district_id, 's_county')
        print(place, 'address')
        print(mobile, 'phone')
        print(email, 'email_number')
        print(default, 'default')
        # 3校验参数
        if not all([receiver, place, mobile, email, default]):
            return http.HttpResponseBadRequest('缺少必要参数')
        print(111)
        if mobile:
            if not re.match(r'^1[3-9]\d{9}$', mobile):
                return http.HttpResponseBadRequest('参数tel有误')
            print(222)
        try:
            address = Address.objects.create(
                user=request.user,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                # tel=default,
                email=email

            )
            print('aaa')
        except Exception as e:
            return http.HttpResponseBadRequest('数据库保存失败')
            # 把收货地址的响应传给前段，实现局部刷新
        address_dict = {
            'id': address.id,
            'name': address.receiver,
            's_province': address.province.name,
            's_city': address.city.name,

            'address': address.place,
            'phone': address.mobile,

            'email_number': address.email
        }
        print(555)
        # # 返回响应结果
        # return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'address': address_dict})

        # 校验参数
        return render(request, 'user_address.html',address_dict)


# class UpdateAddressView(View):
#     """修改收货地址"""
#
#     def put(self, request, address_id):
#         # 获取收货地址对象
#         address = Address.objects.get(id=address_id)
#         # 2判断修改收货地址的是否是当前用户
#         if not (address and address.user == request.user):
#             return http.HttpResponseBadRequest('非法操作')
#
#         # 2获取参数 传来的是json数据
#         json_dict = json.loads(request.body.decode())
#         receiver = json_dict.get('receiver')
#         province_id = json_dict.get('province_id')
#         city_id = json_dict.get('city_id')
#         district_id = json_dict.get('district_id')
#         place = json_dict.get('place')
#         mobile = json_dict.get('mobile')
#         tel = json_dict.get('tel')
#         email = json_dict.get('email')
#
#         # 3校验参数
#         if not all([receiver, district_id, province_id, city_id, mobile, place]):
#             return http.HttpResponseBadRequest('缺少必要参数00')
#         # 验证手机号
#         if not re.match(r'^1[3-9]\d{9}$', mobile):
#             return http.HttpResponseBadRequest('手机号格式不对')
#         # 验证固定电话
#         if tel:
#             if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
#                 return http.HttpResponseBadRequest('tel参数错误')
#         # 验证邮箱
#         if email:
#             if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
#                 return http.HttpResponseBadRequest('邮箱错误')
#
#         # 3更新地址
#         try:
#             Address.objects.filter(id=address_id).update(
#                 user=request.user,
#                 title=receiver,
#                 receiver=receiver,
#                 province_id=province_id,
#                 city_id=city_id,
#                 district_id=district_id,
#                 place=place,
#                 mobile=mobile,
#                 tel=tel,
#                 email=email
#             )
#         except Exception as e:
#             return http.JsonResponse({'cdoe': RETCODE.DBERR, 'errmsg': '更新地址失败'})
#
#         # 4返回json响应数据
#         address = Address.objects.get(id=address_id)
#         address_dict = {
#             'id': address.id,
#             'title': address.receiver,
#             'receiver': address.receiver,
#             'province': address.province.name,
#             'city': address.city.name,
#             'district': address.district.name,
#             'place': address.place,
#             'mobile': address.mobile,
#             'tel': address.tel,
#             'email': address.email,
#
#         }
#         return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '更新地址成功', 'address': address_dict})
#
#     def delete(self, request, address_id):
#         """删除收货地址"""
#         address = Address.objects.get(id=address_id)
#         if not (address and address.user == request.user):
#             return http.HttpResponseBadRequest('非法操作')
#
#         try:
#             address.is_deleted = True
#             address.save()
#         except Exception as e:
#             return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '删除收货地址失败'})
#         return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除成功'})


# class DefaultAddressView(View):
#     def put(self, request, address_id):
#         """设置默认地址"""
#         address = Address.objects.get(id=address_id)
#         if not (address and address.user == request.user):
#             return http.HttpResponseBadRequest('非法操作')
#
#         try:
#             request.user.default_address = address
#             request.user.save()
#             # print('qweqweqwe')
#         except Exception as e:
#             return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '默认地址设置失败'})
#         return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '默认地址设置成功'})



